package com.industrial.white.handler;

import com.industrial.common.core.utils.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.data.redis.core.RedisTemplate;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MybatisWhitelistConvHandler extends BaseTypeHandler<String> {
    private RedisTemplate<String, String> redisTemplate;

    public MybatisWhitelistConvHandler(){
        this.redisTemplate = SpringUtils.getBean("redisTemplate");
    }
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType) throws SQLException {

    }

    @Override
    public String getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String string = resultSet.getString(s);
        if(StringUtils.isNotBlank(string)){
            String[] split = string.split(",");
            if(split.length > 0){
                StringBuilder stringBuilder = new StringBuilder();
                for(int i = 0;i<split.length ;i++){
                    stringBuilder.append((String) redisTemplate.opsForHash().get("whitelist",split[i])).append(",");
                }
                stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                return stringBuilder.toString();
            }
        }

        return "";
    }

    @Override
    public String getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return null;
    }

    @Override
    public String getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }
}
